import base64
import hashlib
import hmac
import time
import requests
from pipes import quote

from llm.entity.dto.DeviceCtlDTO import DeviceCtlDTO


class DeviceService:
    @classmethod
    def create_common_token(cls, params):
        access_key = base64.b64decode(params['author_key'])

        version = params['version']
        user_id = params['user_id']

        res = f'userid/{user_id}'
        et = int((time.time() + 365 * 24 * 3600))  # Expiry time 1 year later in seconds
        method = 'sha1'

        key = f'{et}\n{method}\n{res}\n{version}'

        sign = hmac.new(access_key, key.encode('utf-8'), hashlib.sha1).digest()
        sign = base64.b64encode(sign).decode('utf-8')

        res = quote(res)
        sign = quote(sign)

        token = f'version={version}&res={res}&et={et}&method={method}&sign={sign}'

        return token

    @classmethod
    def oneNET_device_control(cls, device_data: DeviceCtlDTO):
        """
        用于和嵌入式组目前使用的OneNET平台进行通信，实现设备控制
        :param device_data: DeviceData类型的实例，包含product_id, device_name和params
        :return:
        """
        # 常量参数，用于平台认证，后续可能需要修改
        auth_params = {
            'author_key': '3fx80epufCmzt+UlIXNAOeieAkuVBgXyfWoK2ZdJWNiRHpnhPxC4wXH8ARqEbP06A72goZx0coxqJ1z+lPGVGw==',
            'version': '2022-05-01',
            'user_id': '400578',
        }

        url = 'https://iot-api.heclouds.com/thingmodel/set-device-property'
        headers = {
            'authorization': cls.create_common_token(params=auth_params)
        }

        # 从 DeviceData 实例中提取所需数据
        data = {
            'product_id': device_data.product_id,
            'device_name': device_data.device_name,
            'params': device_data.params
        }

        response = requests.post(url, headers=headers, json=data)

        if response.status_code == 200:
            print(data['params'])
            print(f"设备控制成功,返回数据：{response.json()}")
            return {
                "success": True,
                "message": "设备控制成功",
                "data": data['params']
            }
        else:
            print(f"Error: {data['params']}")
            return {
                "success": False,
                "message": "设备控制失败",
                "data": data['params']
            }

        # 测试用
        # print(f"接收到数据{product_id},{device_name},{params}")
        # url = f"http://localhost:8080/test"
        # response = requests.post(url=url, json={
        #     "product_id": product_id,
        #     "device_name": product_id,
        #     "params": params
        # })
        # if response.status_code == 200:
        #     data = response.json()
        #     if 'result' in data:
        #         print(data['result'])
        #         return "测试成功"
        # else:
        #     # 请求失败的错误处理
        #     print(f"oneNET_device_control:错误,response:{response}")
        #     return "测试失败"
